﻿using WJSHWebApi.Common;
using WJSHWebApi.Common.Log4netHelper;
using log4net;
using log4net.Core;
using log4net.Layout;
using log4net.Layout.Pattern;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;

namespace WJSHWebApi
{
    public class LogClass
    {
        public static List<LogClass> logClasses = new List<LogClass>();
      
        public List<string> Logs { get; set; }
        private int logsNumber { get; set; }
        private ILog infolog { get; set; }

        private static readonly ILog OverLog = CustomRollingFileLogger.GetCustomLogger($"OverAll-info");
        private string logName { get; set; }
        public string devid { get; set; }
      
        public LogClass(string logname,int number= 0, string devId=null)
        {
            this.devid = devId;
            logName = logname;
            Logs = new List<string>();
            logsNumber = number;
            infolog = CustomRollingFileLogger.GetCustomLogger($"{logName}-info");
            logClasses.Add(this);
        }
      
        public void Push(string msg)
        {
            Task.Factory.StartNew(() =>
            {
                lock ("PushLock")
                {
                    try
                    {
                        if (logsNumber != 0)
                        {
                            Logs.Add(msg);
                            while (Logs.Count > logsNumber)
                            {
                                Logs.RemoveAt(0);
                            }
                        }
                        infolog.Debug(msg);
                    }
                    catch (Exception)
                    {

                    }
                }
            });
        }
        public void PushEx(Exception ex)
        {
            string errorMsg = BeautyErrorMsg(ex);
            Push(errorMsg);
        }
        
        /// <summary>
        /// Exception
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private static string BeautyErrorMsg(Exception ex)
        {
            string errorMsg = $"{DateTime.Now.ToString()}：【异常类型】:{ex.GetType().Name}\r\n【异常信息】:{ex.Message}\r\n【堆栈调用】:{ex.StackTrace}";
            return errorMsg;
        }


        static object lockobj = new object();
        public static void StaticPush(string msg)
        {
            Task.Factory.StartNew(() =>
            {
                lock (lockobj)
                {
                    OverLog.Debug(msg);
                }
            });
        }

        public static void StaticPushEx(Exception ex)
        {
            string errorMsg = BeautyErrorMsg(ex);
            StaticPush(errorMsg);
        }

    }
}
